package com.itheima.mall.api.ums;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mall.mapper.ums.UmsMenuMapper;
import com.itheima.mall.mapper.ums.UmsRoleMenuRelationMapper;
import com.itheima.mall.pojo.ums.UmsMenu;
import com.itheima.mall.pojo.ums.UmsRoleMenuRelation;
import com.itheima.mall.vo.R;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsRoleMenuRelationServiceImpl implements UmsRoleMenuRelationServiceApi {

    @Autowired
    UmsRoleMenuRelationMapper umsRoleMenuRelationMapper;

    @Autowired
    UmsMenuMapper umsMenuMapper;

    @Override
    public R UmsRoleAllocMenu(Long[] menuIds, Long roleId) {

        int flag = 0;
        for (Long menuId : menuIds) {
            UmsRoleMenuRelation umsRoleMenuRelation = new UmsRoleMenuRelation();
            umsRoleMenuRelation.setMenuId(menuId);
            umsRoleMenuRelation.setRoleId(roleId);
            int i = umsRoleMenuRelationMapper.insert(umsRoleMenuRelation);
            flag += i;
        }

        if (flag>0){
            return R.succeed("","创建成功");
        }

        return R.error("创建失败");
    }

    @Override
    public R UmsRoleListMenu(Long id) {

        LambdaQueryWrapper<UmsRoleMenuRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ObjectUtil.isNotNull(id),UmsRoleMenuRelation::getRoleId,id);
        List<UmsRoleMenuRelation> umsRoleMenuRelations = umsRoleMenuRelationMapper.selectList(lqw);

        List<UmsMenu> umsMenuList = new ArrayList<>();
        for (UmsRoleMenuRelation umsRoleMenuRelation : umsRoleMenuRelations) {
            UmsMenu umsMenu = umsMenuMapper.selectById(umsRoleMenuRelation.getMenuId());
            umsMenuList.add(umsMenu);
        }
        return R.succeed(umsMenuList,"查找成功");
    }
}
